import { Injectable } from '@angular/core';
import { Graph, ToolsView, EdgeView } from '@antv/x6';

export interface ContextMenuToolOptions extends ToolsView.ToolItem.Options {
  x: number;
  y: number;
  menu?: any;
  onHide?: (this: NodeContextMenuTool) => void;
  onClick?: (this: NodeContextMenuTool, event: Event) => void;
}

class NodeContextMenuTool extends ToolsView.ToolItem<EdgeView, ContextMenuToolOptions> {
  private knob!: HTMLDivElement;

  render() {
    super.render();
    this.knob = ToolsView.createElement('div', false) as HTMLDivElement;
    this.knob.style.position = 'absolute';
    this.container.appendChild(this.knob);
    this.updatePosition(this.options);
    setTimeout(() => {
      this.toggleTooltip(true);
    });
    return this;
  }

  private toggleTooltip(visible: boolean) {

    document.removeEventListener('mousedown', this.onMouseDown);

    if (visible) {
      const div = ToolsView.createElement('div', false);
      div.setAttribute('className', 'ant-dropdown');

      div.innerHTML = `
      <ul class="ant-dropdown-menu ant-dropdown-menu-root ant-dropdown-menu-light ant-dropdown-menu-vertical">
      <li class="ant-dropdown-menu-item" custom-type="2">添加链接桩</li>
      <li class="ant-dropdown-menu-item" custom-type="1">删除</li>
      </ul>
      `;
      // div.innerHTML = this.options.menu;
      this.knob.appendChild(div);

      div.querySelectorAll('li')!.forEach(node => {
        node.addEventListener('click', (event) => {
          if (this.options.onClick) {
            this.options.onClick.call(this, event);
          }
        });
      });
      document.addEventListener('mousedown', this.onMouseDown);
    }
  }

  private updatePosition(pos?: { x: number; y: number; }) {
    const style = this.knob.style;
    if (pos) {
      style.left = `${pos.x}px`;
      style.top = `${pos.y}px`;
    } else {
      style.left = '-1000px';
      style.top = '-1000px';
    }
  }

  private onMouseDown = (e: MouseEvent) => {
    setTimeout(() => {
      this.updatePosition();
      this.toggleTooltip(false);
      if (this.options.onHide) {
        this.options.onHide.call(this);
      }
    }, 200);
  };
}

NodeContextMenuTool.config({
  tagName: 'div',
  isSVGElement: false,
});

Graph.registerNodeTool('nodeContextmenu', NodeContextMenuTool, true);
